import React, { useEffect, useState } from "react";
import { get_synthesis, saveOrUpdate } from "@/api/emr/index";
import { BasicTable, useTable } from "@/components/Table";
import cloneDeep from "lodash/cloneDeep";
import { Card, Col, Row, Radio, Checkbox, Button } from "antd";

export default function emr() {
	const [synthesisList, setSynthesisList] = useState({
		nameEn: "",
		answer: []
	});
	const [loading, setLoading] = useState(true);
	const [tableRows, setTableRows] = useState([]);
	const [tableCols, setTableCols] = useState([]);

	// 自定义渲染函数，根据 dataType 进行不同的渲染
	const renderColumn = (text: string, record: any, index: any) => {
		const column = tableCols[index];
		if (column.dataType === "OPTIONS") {
			if (Array.isArray(text)) {
				// 获取选中的 itemId
				const selectedItemId = text.find(item => item.result)?.itemId;
				console.log(selectedItemId);
				console.log(text);
				return (
					<Radio.Group onChange={e => handleRadioChange(record, column.dataIndex, e.target.value)}>
						{text.map(item => (
							<Radio key={`${record.blockId}-${column.dataIndex}-${item.itemId}`} value={item.itemId}>
								{item.nameCn}
							</Radio>
						))}
					</Radio.Group>
				);
			}
		} else if (column.dataType === "SUBJECT") {
			return (
				<div>
					{record[column.dataIndex].nameCn} ({record[column.dataIndex].nameEn})
				</div>
			);
		}
		return text;
	};
	const columns = tableCols.map((col, index) => ({
		...col,
		render: (text: string, record: any) => renderColumn(text, record, index)
	}));

	// 配置 table
	const [registerTable] = useTable({
		dataSource: tableRows,
		columns,
		bordered: true,
		pagination: false
	});

	// table 组件中 Radio 变化的函数
	const handleRadioChange = (record: any, columnDataIndex: string, value: number) => {
		// 删除 record 的 key 属性
		const newRecord = { ...record };
		delete newRecord.key;
		// 创建一个新的数据副本
		const newData = cloneDeep(synthesisList);
		const blockIndex = newData.answer.findIndex(block => block.blockId === newRecord.blockId);
		if (blockIndex !== -1) {
			// 更新 tableRows 中的 result 字段
			const tableRowIndex = newData.answer[blockIndex].tableRows.findIndex(row =>
				row[columnDataIndex]?.some(item => item.itemId === value)
			);
			if (tableRowIndex !== -1) {
				const items = newData.answer[blockIndex].tableRows[tableRowIndex][columnDataIndex];
				items.forEach(item => {
					if (item.itemId === value) {
						item.result = true;
					} else {
						item.result = false;
					}
				});
			}
			// 更新状态
			setSynthesisList(newData);
		} else {
			console.error("未找到匹配的 block", record);
		}
	};

	// card 组件中 Checkbox 变化的函数
	const handleChange = (index: number, p: number, i: number, event: any) => {
		console.log(index, p, i, event);
		// 创建一个新的数据副本，避免直接修改状态
		const newData = cloneDeep(synthesisList);
		// 更新相应索引的数据
		newData.answer[index].subjects[p].items[i].result = event.target.checked;
		// 更新状态
		setSynthesisList(newData);
	};

	// 获取页面组件
	const getComponent = (data: any, index: number, p: number) => {
		let types: any = [];
		data.forEach(item => {
			types.push(item.inputType);
		});
		if (types.includes("CHECKBOX")) {
			let defaultValue = data.filter(item => item.result).map(v => v.itemId);
			return (
				<Checkbox.Group defaultValue={defaultValue}>
					{data.map((v, i) => (
						<Checkbox
							key={`${index}-${p}-${i}-${v.itemId}`}
							checked={v.result}
							onChange={e => handleChange(index, p, i, e)}
							value={v.itemId}
							style={{ marginBottom: "10px" }}
						>
							{v.nameCn}
						</Checkbox>
					))}
				</Checkbox.Group>
			);
		} else if (types.includes("RADIO")) {
			let defaultValue = null;
			for (let item of data) {
				if (item.result) {
					defaultValue = item.itemId;
					break;
				}
			}
			return (
				<Radio.Group defaultValue={defaultValue}>
					{data.map((v, i) => (
						<Radio
							key={`${index}-${p}-${i}-${v.itemId}`}
							onChange={e => handleChange(index, p, i, e)}
							value={v.itemId}
							style={{ marginBottom: "10px" }}
						>
							{v.nameCn}
						</Radio>
					))}
				</Radio.Group>
			);
		} else {
			console.log("TEXT");
		}
	};

	// 提交
	const submit = async () => {
		const newData = { ...synthesisList };
		newData.rcptId = "15936";
		newData.patId = "23539";
		newData.answer = newData.blocks;
		await saveOrUpdate(newData);
		location.reload();
	};

	// 立即执行的函数
	useEffect(() => {
		const get_list = async () => {
			const res = await get_synthesis({ formId: "2", rcptId: "15936" });
			console.log(res);
			res.answer = res.blocks;
			setSynthesisList(res);
			res.answer.forEach(item => {
				if (item.tableRows) {
					const newTableRows = item.tableRows.map(row => ({ ...row, blockId: item.blockId }));
					setTableRows(newTableRows);
				}
				if (item.tableCols) {
					setTableCols(item.tableCols);
				}
			});
			setLoading(false);
		};
		get_list();
	}, []);

	return (
		<div className="page block overflow-auto">
			<div className="header">
				<div className="text-center font-size-9">{synthesisList.nameCn}</div>
				<Button type="primary" onClick={submit}>
					提交
				</Button>
				{synthesisList.answer.map((item, index) => (
					<div key={item.blockId}>
						<div className="font-size-5">{item.nameCn}</div>
						{item.tableCols ? (
							<BasicTable columns={columns} register={registerTable}></BasicTable>
						) : (
							<Row gutter={16}>
								{item.subjects &&
									item.subjects.map((o, p) => (
										<Col span={4} key={`${index}-${p}-${o.subjsId}`}>
											<Card title={o.nameCn} style={{ marginTop: 16, overflow: "auto" }} loading={loading}>
												{getComponent(o.items || [], index, p)}
											</Card>
										</Col>
									))}
							</Row>
						)}
					</div>
				))}
			</div>
		</div>
	);
}
